<template>
    <!-- 分销商列表 -->
    <div>
        <div class="daohang">
            <div class="tit">
                <el-steps :active="step" process-status="finish" finish-status="success" simple>
                    <el-step title="选择商品分类"></el-step>
                    <el-step title="填写商品信息"></el-step>
                    <el-step title="设置商品属性"></el-step>
                    <el-step title="设置商品规格"></el-step>
                    <el-step title="设置商品库存"></el-step>
                </el-steps>
            </div>

            <div class="cateSelect" v-show="step == 0">
                <div class="jichu">
                    <div class="shu"></div>
                    <h4>商品分类</h4>
                </div>
                <div class="fenlei">
                    <el-tree-select v-model="form.categoryId" :data="cateOption" @current-change="selected"
                        :render-after-expand="false" placeholder="请选择分类" />
                </div>
                <div class="fenlei">

                    <span class="shangpinmingcheng"><span class="xinghao">*</span>
                        商品分类</span><span v-for="(item, index) in pathLabels" style="margin-left: 5px">
                        {{ item }}
                        <b v-show="index < pathLabels.length - 1">></b>
                    </span>
                </div>

            </div>
            <div class="info" v-show="step == 1">
                <div class="jichu">
                    <div class="shu"></div>
                    <h4>商品信息</h4>
                </div>
                <div class="demo-input-suffix">
                    <span class="shangpinmingcheng"><span class="xinghao">*</span>商品名称</span>
                    <el-input v-model="form.name" class="shurumincheng" placeholder="输入商品名称" />
                </div>
                <div class="demo-input-suffix">
                    <span class="shangpinmingcheng"><span class="xinghao">*</span>原价</span>
                    <el-input v-model="form.originPrice" type="number" class="shurumincheng" placeholder="输入商品原价" />
                </div>
                <div class="demo-input-suffix">
                    <span class="shangpinmingcheng"><span class="xinghao">*</span>现价</span>
                    <el-input v-model="form.price" type="number" class="shurumincheng" placeholder="输入商品现价" />
                </div>
                <div class="demo-input-suffix top">
                    <span class="shangpinmingcheng"><span class="xinghao"></span>商品简介</span>
                    <el-input v-model="form.description" type="textarea" class="shurumincheng" placeholder="输入商品简介" />
                </div>
                <div class="fenlei">
                    <span class="shangpinmingcheng"><span class="xinghao">*</span> 商品主图片</span>
                    <el-row :gutter="10">
                        <el-col :offset="1" :span="3">
                            <el-card style="width: 180px;" :body-style="{ padding: '10px' }">
                                <SingleUpload class="avatar-uploader" @changeUrl="changeUrl" />
                            </el-card>
                        </el-col>
                    </el-row>

                    <p>最多添加1张图，建议图片尺寸800*800，图片大小不超过2M</p>
                </div>
                <div class="fenlei">
                    <span class="shangpinmingcheng"><span class="xinghao">*</span>详细介绍图片</span>
                    <el-row :gutter="10">
                        <el-col :offset="1" :span="3" v-for="(item, index) in pictures" key="item">
                            <el-card style="width: 180px;height: 200px;" :body-style="{ padding: '10px' }">
                                <SingleUpload class="avatar-uploader" @changeUrl="addUrl" />
                                <div class="bottom" v-if="item">
                                    <el-button type="text" class="button"
                                        @click="handlePictureRemove(index)">删除图片</el-button>
                                </div>
                            </el-card>
                        </el-col>

                    </el-row>
                    <p>最多添加6张介绍图，建议图片大小不超过2M</p>
                </div>

            </div>
            <div class="attr page" v-show="step == 2">
                <div class="top">
                    <div class="jichu">
                        <div class="shu"></div>
                        <h4>商品属性</h4>
                    </div>
                    <div class="add">
                        <el-button color="#ed742f" class="font-white" @click="addAttr">添加属性</el-button>
                    </div>
                </div>
                <el-table :data="form.attrList" stripe style="width: 97%" empty-text="无属性">
                    <el-table-column label="属性名称" prop="name">
                        <template #default="scope">
                            <el-input placeholder="请输入名称" class="wid-180" v-model="scope.row.name"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="属性值" prop="value">
                        <template #default="scope">
                            <el-input placeholder="请输入属性值" class="wid-180" v-model="scope.row.value"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作">
                        <template #default="scope">
                            <el-button link :dark="true" class="font-main" @click="delAttr(scope.$index)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>

            </div>
            <div class="stock page" v-show="step == 3">
                <div class="top">
                    <div class="jichu">
                        <div class="shu"></div>
                        <h4>设置商品规格</h4>
                    </div>
                    <div class="add">
                        <el-button color="#ed742f" class="font-white" @click="addSpec">添加规格项</el-button>
                    </div>
                </div>
                <el-table :data="specList" stripe style="width: 97%" empty-text="请添加规格">
                    <el-table-column label="规格名" prop="name">
                        <template #default="scope">
                            <el-input placeholder="请输入名称" class="wid-180" v-model="scope.row.name"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="规格值" prop="value">
                        <template #default="scope">
                            <div class="val">
                                <el-tag v-for="tag in scope.row.values" :key="tag" class="mx-1" closable
                                    :disable-transitions="false" @close="handleClose(scope.$index, tag.value)">
                                    {{ tag.value }}
                                </el-tag>
                                <el-input v-if="scope.row.inputVisible" ref="InputRef" v-model="inputValue" class="w-20"
                                    size="small" @keyup.enter="handleInputConfirm(scope.$index)"
                                    @blur="handleInputConfirm(scope.$index)" />
                                <el-button v-else class="button-new-tag ml-1" size="small" @click="showInput(scope.$index)">
                                    添加规格值
                                </el-button>
                            </div>

                        </template>
                    </el-table-column>
                    <el-table-column label="操作" align-items="right">
                        <template #default="scope">
                            <el-button link :dark="true" class="font-main" @click="delSpec(scope.$index)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="stock page" v-show="step == 4">
                <div class="top">
                    <div class="jichu">
                        <div class="shu"></div>
                        <h4>设置商品库存</h4>
                    </div>
                </div>
                <el-table :data="data" stripe style="width: 97%" empty-text="请返回上一步设置规格">
                    <template v-if="specs.length > 0" v-for="column in specs">
                        <el-table-column :label="column.title" :prop="column.dataKey" :width="column.width" align="center">

                        </el-table-column>
                    </template>

                    <el-table-column label="specIds" prop="specIds" align="center"></el-table-column>

                    <el-table-column label="商品编码" prop="sn" align="center">
                        <template #default="scope">
                            <el-input placeholder="请输入编码" class="wid-180" v-model="scope.row.sn"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="价格" prop="price" align="center">
                        <template #default="scope">
                            <el-input placeholder="请输入价格" type="number" class="wid-180"
                                v-model="scope.row.price"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="库存" prop="stock" align="center">
                        <template #default="scope">
                            <el-input placeholder="请输入库存" type="number" class="wid-180"
                                v-model="scope.row.stock"></el-input>
                        </template>
                    </el-table-column>
                </el-table>
            </div>


            <div class="footer">
                <div><el-button v-if="step > 0" color="#ed742f" class="font-white" @click="handlePre">返回</el-button></div>
                <div>
                    <el-button v-if="step < 4" color="#ed742f" class="font-white" @click="handleNext">下一步</el-button>
                    <el-button v-if="step == 4" color="#ed742f" class="font-white" @click="save">提交</el-button>
                </div>

            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { computed, nextTick, onBeforeMount, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import SingleUpload from "@/components/Upload/SingleUpload.vue";
import { ElInput } from 'element-plus'
import productClassifyService from '@/service/productClassifyService'
import productService from '@/service/productService'

import type { Column } from 'element-plus'
import router from '@/router';
onBeforeMount(() => {
    productClassifyService.cascade().then((res: any) => {
        cateOption.value = res.data.data
    })
})
const form = reactive({
    categoryId: undefined,
    description: undefined,//简介
    detail: undefined,//详细内容图片地址
    name: undefined,
    originPrice: undefined,
    picUrl: undefined,
    distribution:0,
    price: undefined,
    attrList: [
        {
            attributeId: undefined,
            name: "",
            value: ""
        }
    ],
    specList: [
        {
            attributeId: -1,
            id: "",//临时id
            name: "",
            value: ""
        }
    ],
    skuList: [
        {
            name: undefined,//拼接规格名
            specIds: undefined,//拼接规格临时id
            picUrl: undefined,
            price: undefined,
            sn: undefined,
            stock: undefined,
        }
    ],
})
//保存属性和规格的请求方法
const saveAttr = async (formData: Array<any>, attrList: any, type: number) => {
    let attr_new = formData.map((item) => { return { attributeId: item.attributeId, name: item.name } })
    if (attrList.value.length == 0 || JSON.stringify(attrList.value) != JSON.stringify(attr_new)) {
        await productClassifyService.batch(form.categoryId, type, formData.map((item) => { return { name: item.name } })).then((res: any) => {
            productClassifyService.attributes(form.categoryId, type).then((resp: any) => {
                if (resp.data.data.length > 0) {
                    resp.data.data.forEach((item: any) => {
                        formData.forEach((ite: any) => {
                            if (item.name == ite.name) {
                                ite.attributeId = item.id
                            }
                        })
                    })
                    let attr_ = formData.map((item) => { return { attributeId: item.attributeId, name: item.name } })
                    attrList.value = attr_;
                    if (type == 1) {
                        insertFormSpec()
                        stockTableCreate()
                    }

                }
            })
        })
    }
}

//提交步骤
const step = ref(0)
const handleNext = () => {
    if (step.value == 3) {
        saveAttr(specList, specList_, 1)
    }
    if (step.value == 2) {
        if (form.categoryId == undefined) {
            ElMessage.error("请先选择类型")
            return
        }
        else {
            saveAttr(form.attrList, attrList, 2)
        }
    }
    step.value = step.value + 1;
}
const handlePre = () => {
    if (step.value == 3) {
        insertFormSpec()
    }
    step.value = step.value - 1;
}
//第一步
//分类选择
const cateOption = ref([
    {
        value: "1",
        label: "请等待加载",
        children: []
    }
])
//路径显示数组
const pathLabels = ref([])
//选择后添加字符串进路径显示数组
const selected = (data: any, node: any) => {
    pathLabels.value = []
    let putPar = (node: any) => {
        if (Object.prototype.toString.call(node.parent) === '[object Object]') {
            pathLabels.value.unshift(node.data.label)
            putPar(node.parent)
        }
    }
    putPar(node)
}
//第二步
//主视图上传地址
const changeUrl = (val: any) => {
    form.picUrl = val
}
//详情图片数组
const pictures = reactive([""])
//删除图片
const handlePictureRemove = (index: number) => {
    pictures.splice(index, 1)
}
//添加图片
const addUrl = (val: any) => {
    if (val == '') {
        return
    }
    pictures.unshift(val)
    form.detail = pictures.filter((item)=>item!="").join(",")
    console.log(form.detail);
    
}
//第三步
//添加属性
const addAttr = () => {
    form.attrList.push({ attributeId: undefined, name: "", value: "" })
}
const delAttr = (index: any) => {
    form.attrList.splice(index, 1)
}
//请求返回的后端属性值
const attrList = ref([])
const specList_ = ref([])
//第四部
//上传规格
const specList = reactive([
    {
        attributeId: undefined,
        id: undefined,//临时id
        name: undefined,
        values: [],
        inputVisible: false
    }
])
//表格数据遍历放入form表单中
const insertFormSpec = () => {
    form.specList = [];
    specList.forEach((element, rowIndex) => {
        element.values.forEach((item, index) => {
            item.id = "tid_" + (rowIndex + 1) + "_" + (index + 1);
            form.specList.push({
                attributeId: element.attributeId,
                id: item.id,
                name: element.name,
                value: item.value
            })
        })
    });
}
//添加删除
const addSpec = () => {
    specList.push({
        attributeId: undefined,
        id: undefined,//临时id
        name: undefined,
        values: [],
        inputVisible: false
    })
}
const delSpec = (index: any) => {
    specList.splice(index, 1)
}
//删除规格项
const handleClose = (index: number, tag: string) => {
    let id;
    specList[index].values.forEach((item: any, idx: any) => {
        if (item.value == tag)
            id = idx;
    })
    specList[index].values.splice(id, 1)
}
//点击输入相关
const inputValue = ref('')
const InputRef = ref<InstanceType<typeof ElInput>>()
const inputVisible = ref(false)
const showInput = (index: any) => {
    specList[index].inputVisible = true
    nextTick(() => {
        InputRef.value!.input!.focus()
    })
}
//输入插入
const handleInputConfirm = (index: number) => {
    if (inputValue.value) {
        if (specList[index].values.length >= 3) {
            ElMessage.error("最多支持3组规格")
            return;
        }
        specList[index].values.push({ id: '', value: inputValue.value })
    }
    specList[index].inputVisible = false
    inputValue.value = ''
}
const digui = function (list: any, preList: any, i: number, data: any) {
    if (list.length == i) {
        let obj = {
            name: undefined,//拼接规格名
            specIds: "",//拼接规格临时id
            picUrl: undefined,
            price: "",
            sn: "",
            stock: ""
        }
        preList.forEach((item: any, index: any) => {
            let name = "spec_" + (index + 1)
            obj[name] = item.value;
            obj.name = obj.name + (index == 0 ? item.value : ";" + item.value)
            obj.specIds = obj.specIds + (index == 0 ? item.id : "|" + item.id)
        })
        data.push(obj)
    } else {
        list[i].forEach((preValue: any) => {
            let preList_ = [...preList, preValue]
            digui(list, preList_, i + 1, data)
        })
    }
}
const data: Array<Object> = reactive([]);

const stockTableCreate = () => {
    let list = [] as Array<Array<string>>
    specs.splice(0, specs.length)
    specList.forEach((spec: any, i: any) => {
        if (spec.values.length > 0) {
            specs.push({
                key: "spec_" + (i + 1),
                title: spec.name,
                dataKey: "spec_" + (i + 1),
                width: 100,
            })
            list.push([...spec.values])
        }
    })
    data.splice(0, data.length)
    digui(list, [], 0, data)
}
//库存表相关
const specs: Column<any>[] = reactive([])

//提交
const save = () => {
    form.skuList = data.map((item) => {

        return {
            name: item.name,//拼接规格名
            specIds: item.specIds,//拼接规格临时id
            price: item.price,
            sn: item.sn,
            stock: item.stock,
        }
    })
    productService.addNew(form).then((res: any) => {
        console.log(res);
        ElMessage({
            message: "添加成功",
            type: 'success',
        })
    })
    router.push("/list")
}
</script>

<style scoped lang="less">
.tit {
    width: 100%;
    background-color: #fff;
    margin-bottom: 20px;

    .el-step {

        color: #8c939d;
    }

    .active {
        color: #ed742f;
    }
}

.footer {
    padding: 30px 40px;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.w-20 {
    width: 60px;
}

.val {
    display: flex;
    align-items: center;
}

//商品分类

p {
    margin-left: 3%;
    font-size: 6px;
    color: #8c939d;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

// .el-icon.avatar-uploader-icon {
//     font-size: 28px;
//     color: #8c939d;
//     width: 160px;
//     height: 178px;
//     text-align: center;
// }

.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.avatar-uploader {
    // margin-left: 40px;
}

.daohang {
    width: 100%;
    // border: #ed742f solid 1px;

    .xuanze {
        margin-left: 2%;
        color: #ed742f;
        border: #ed742f 1px solid;
    }

    .fenlei {
        margin-top: 50px;
    }

    .xinghao {
        color: red;
    }

    .demo-input-suffix {
        margin-top: 20px;
        display: flex;
        align-items: center;

        &.top {
            align-items: start;
        }
    }

    .shurumincheng {

        width: 350px;
    }

    .shangpinmingcheng {
        width: 80px;
        text-align: right;
        margin-left: 3%;
        margin-right: 1%;

    }

    .jichu {
        display: flex;
    }

    .shu {
        margin-right: 10px;
        width: 5px;
        height: 50px;
        background-color: #ed742f;
    }

    .page {
        .top {
            display: flex;
            justify-content: space-between;
            align-items: center;

            .add {
                margin-right: 40px;
            }
        }
    }

}
</style>